import sys
sys.path.append("../utils")

config_path = "./config.cfg"
import ConfigParser
import time
import datetime as dt
from matplotlib.dates import date2num
from matplotlib.dates import num2date

import matplotlib.pyplot as plt
import numpy as np

import get_data

def plot_power(data_tab):
    """
    Simple plotting of the power distribution over a one year period
    """
    start_day=dt.datetime(2011,01,01)
    stop_day=dt.datetime(2012,01,01)
    r1 = range(0,2100,100)
    r2 = range(100,2200,100)
    rs = zip(r1, r2)
    fig, axs = plt.subplots(1,1)
    ax = axs
    dats = []
    for low, high in rs:
        over_filter = ["(ActivePowerAvg >= " + str(low) + ")",
                       "(ActivePowerAvg <" + str(high) + ")"]
        time_filt = ["(Time > " + str(date2num(start_day)) + ")"]
        time_filt += ["(Time < " + str(date2num(stop_day)) + ")"]
        filt = over_filter + time_filt
        dat = get_data.filter_h5data(data_tab, filt)
        dats.append(float(len(dat)))
    total_dats = sum(dats)
    ax.bar(r1, [dat / total_dats * 100 for dat in dats ], width = 50)
    ax.set_title("Power Distribution")
    return

def plot_gear_temp(data_tab):
    colors = ("#FEE5D9", "#FCAE91", "#FB6A4A", "#CB181D",)
    start_pow = 100
    stop_pow = 2000
    step_pow = 500
    r1 = range(start_pow, stop_pow, step_pow)
    r2 = range(start_pow + step_pow, stop_pow + step_pow, step_pow)
    start_day = dt.datetime(2009,01,01)
    stop_day = dt.datetime(2010,07,01)
    rs = zip(r1, r2)
    low = 200
    high = 2000
    fig, axs = plt.subplots(1,1)
    ax = axs
    for i, (low, high) in list(enumerate(rs)):
        time_filt = ["(Time >= " + str(date2num(start_day)) + ")",
                "(Time < " + str(date2num(stop_day)) + ")"]
        over_filter = ["(ActivePowerAvg >= " + str(low) + ")",
                "(ActivePowerAvg <" + str(high) + ")"]
        filt = over_filter + time_filt
        dat = get_data.filter_h5data(data_tab, filt)
        print low
        print high
        print " Mean: ",
        print np.mean(dat["GearBearTempAvg"]),
        print " Variance: ",
        print np.var(dat["GearBearTempAvg"])
        ax.plot(num2date(dat["Time"]), dat["GearBearTempAvg"], 'o', ms=6,
                label=str(int(float(low)/2000*100)) + '-' + str(int(float(high)/2000*100)) + "%", color=colors[i], markeredgewidth=0.1)#markeredgecolor=colors[i])
    #ax.set_title("Gear bearing temperature at different power levels")
    #ax.set_title("Plot of raw data")
    ax.set_ylabel("Gear bearing temperature [$^\circ$C]")
    axs.spines['top'].set_visible(False)
    axs.spines['right'].set_visible(False)
    axs.get_xaxis().tick_bottom()
    axs.get_yaxis().tick_left()
    ax.legend(loc=3, fancybox=True)
    fig.autofmt_xdate()

def look_at_it():
    start_time = time.time()
    config = ConfigParser.ConfigParser()
    config.read(config_path)
    turbines = config.get("options", "turbines").split(',')
    bin_path = config.get("options", "bin_path")
    h5_file = config.get("options", "h5file")
    f_h5 = bin_path + h5_file
    turbines = "WH1236",
    data_sets = get_data.from_turbines(turbines, f_h5)
    plot_gear_temp(data_sets[0])
    #plot_power(data_sets[0])
    print "Done in:",
    print (time.time() - start_time)
    plt.show()

def main():
    look_at_it()
    return

if __name__=='__main__':
    main()
